package red.yancloud.www.ui.fragment


import android.content.Context
import android.content.Intent
import android.view.View
import androidx.appcompat.widget.AppCompatButton
import androidx.appcompat.widget.LinearLayoutCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.scwang.smartrefresh.layout.header.ClassicsHeader
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener
import com.scwang.smartrefresh.layout.listener.OnRefreshListener
import io.reactivex.Observer
import io.reactivex.disposables.Disposable

import red.yancloud.www.R
import red.yancloud.www.base.BaseFragment
import red.yancloud.www.common.Constants
import red.yancloud.www.internet.api.RedCloudApis
import red.yancloud.www.internet.bean.BookCatalog
import red.yancloud.www.ui.adapter.BookCatalogRecyclerAdapter
import red.yancloud.www.ui.read.EPupReadActivity
import red.yancloud.www.util.NetworkUtils
import red.yancloud.www.util.TimeFormatUtil
import red.yancloud.www.util.ToastUtils
import java.text.SimpleDateFormat
import java.util.*

/**
 * @Org：www.shuhai.com(陕西书海网络科技有限公司)
 * @Author：风不会停息 on 2019/7/23 14:42
 * E_Mail：yh131412hys@163.com
 * Describe：阅读页面侧滑展示的目录页
 * Change：
 * @Version：V1.0
 */
class BookCatalogFragment : BaseFragment() {

    private var page: Int = 1
    private var totalPage: Int = 0
    private lateinit var bookId: String

    private lateinit var ePupReadActivity:EPupReadActivity
    private lateinit var mBookCatalogFragmentBookRV: RecyclerView
    private lateinit var mSmartRefreshLayout: SmartRefreshLayout
    private lateinit var mReload: AppCompatButton
    private lateinit var mViewLoadFail: LinearLayoutCompat

    private lateinit var mAdapter:BookCatalogRecyclerAdapter

    override val layoutId: Int
        get() = R.layout.fragment_book_catalog

    override fun onAttach(context: Context) {
        super.onAttach(context)

        ePupReadActivity = context as EPupReadActivity
    }

    override fun attachView() {

        mBookCatalogFragmentBookRV = parentView.findViewById(R.id.bookCatalogFragment_book_rV)
        mSmartRefreshLayout = parentView.findViewById(R.id.smartRefreshLayout)
        mReload = parentView.findViewById(R.id.reload)
        mViewLoadFail = parentView.findViewById(R.id.errorView)

        initSmartRefreshLayout()
    }

    override fun initData() {

    }

    private fun getCatalogList() {
        RedCloudApis.getInstance().catalog(bookId,page.toString(), "12", object : Observer<BookCatalog> {
            override fun onComplete() {
            }

            override fun onSubscribe(d: Disposable) {
            }

            override fun onNext(t: BookCatalog) {

                if (t.code==Constants.SYSTEM_OK) {

                    mViewLoadFail.visibility=View.GONE
                    mSmartRefreshLayout.visibility=View.VISIBLE

                    if(t.data != null&&t.data.page!=null&& t.data.chapters != null && t.data.chapters.size > 0){

                        totalPage = t.data.page.totalPage
                        if (page==1) {

                            mAdapter.data.clear()
                            mAdapter.addData(t.data.chapters)
                            mSmartRefreshLayout.resetNoMoreData()
                            mSmartRefreshLayout.finishRefresh()
                        }else {

                            mAdapter.addData(t.data.chapters)
                            mSmartRefreshLayout.finishLoadMore()
                        }
                    }else{

                        if (page==1){

                            mSmartRefreshLayout.finishRefresh()
                        }else{

                            ToastUtils.showToast(getString(R.string.data_all_load))
                            mSmartRefreshLayout.finishLoadMore()
                        }
                    }
                }else{

                    ToastUtils.showToast(t.msg)
                    mViewLoadFail.visibility=View.VISIBLE
                    mSmartRefreshLayout.visibility=View.GONE
                }
            }

            override fun onError(e: Throwable) {
            }
        })
    }

    override fun configView() {

        mBookCatalogFragmentBookRV.layoutManager=LinearLayoutManager(mContext,RecyclerView.VERTICAL,false)
        mAdapter = BookCatalogRecyclerAdapter(R.layout.item_book_catalog_list)
        mBookCatalogFragmentBookRV.adapter= mAdapter
        mAdapter.onItemClickListener = object : BaseQuickAdapter.OnItemClickListener{
            override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {

                startActivity(
                    Intent(mContext, EPupReadActivity::class.java)
                        .putExtra("bookId",bookId)
                        .putExtra("firstbookchapterid",(adapter!!.data[position] as BookCatalog.DataBean.ChaptersBean).id)
                )
                ePupReadActivity.mDrawerLayout.closeDrawers()
                ePupReadActivity.finish()
            }
        }

        bookId = arguments!!.getString("bookId")!!
        getCatalogList()
    }

    private fun initSmartRefreshLayout() {

        mSmartRefreshLayout.autoRefresh()

        val mClassicsHeader = mSmartRefreshLayout.refreshHeader as ClassicsHeader
        mClassicsHeader.setLastUpdateTime(Date(System.currentTimeMillis()))
        mClassicsHeader.setTimeFormat(SimpleDateFormat("更新于 MM-dd HH:mm", Locale.CHINA))
        mClassicsHeader.setTimeFormat(TimeFormatUtil("更新于 %s"))
        /*Translate, //平行移动        特点: HeaderView高度不会改变，
            Scale, //拉伸形变            特点：在下拉和上弹（HeaderView高度改变）时候，会自动触发OnDraw事件
            FixedBehind, //固定在背后    特点：HeaderView高度不会改变，
            FixedFront, //固定在前面     特点：HeaderView高度不会改变，
            MatchLayout//填满布局        特点：HeaderView高度不会改变，尺寸充满 RefreshLayout*/
//        mClassicsHeader.spinnerStyle = SpinnerStyle.Scale

//        smartRefreshLayout.setEnableAutoLoadMore(true)//开启自动加载功能（非必须）
        mSmartRefreshLayout.setOnRefreshListener(OnRefreshListener {

            if (!NetworkUtils.isConnected(mContext)) {
                mViewLoadFail.visibility = View.VISIBLE
                ToastUtils.toastNetErrorMsg()
                mSmartRefreshLayout.finishRefresh()
                return@OnRefreshListener
            }
            page=1
            getCatalogList()
        })
        mSmartRefreshLayout.setOnLoadMoreListener(OnLoadMoreListener { refreshLayout ->

            if (page>=totalPage){

                ToastUtils.showToast(getString(R.string.data_all_load))
                mSmartRefreshLayout.finishLoadMoreWithNoMoreData()//将不会再次触发加载更多事件
                return@OnLoadMoreListener
            }

            if (!NetworkUtils.isConnected(mContext)) {
                mViewLoadFail.visibility = View.VISIBLE
                ToastUtils.toastNetErrorMsg()
                mSmartRefreshLayout.finishLoadMore()
                return@OnLoadMoreListener
            }
            page++
            getCatalogList()
        })
    }

}
